// 账号相关 控制器
'use strict'
// 引入 验证码插件 fs模块
const captchapng = require( 'captchapng' );
const fs = require( 'fs' );

// 获取登陆页面
exports.getLoginPage = ( req, res ) => {
  // 读取登陆页面视图
  fs.readFile( './views/login.html', ( err, content ) => {
    if ( err ) {
      console.log( '错误' + err );
      return;
    }
    res.setHeader( 'Content-Type', 'text/html;charset=utf8' );
    res.end( content );
  } );
};

// 登陆
// 1. 获取浏览器传来的参数 post (body-parser 把请求再次包装了)
// 2. 判断验证码
// 3. 判断用户名和密码
exports.login = ( req, res ) => {

  // 获取参数
  const uname = req.body.uname;
  const upwd = req.body.upwd;
  const vcode = req.body.vcode;

  // 判断验证码
  if ( vcode != req.session.vcode ) {
    res.end( "<script>alert('验证码错误!!!');window.location.href='/account/login';</script>" );
    return;
  }

  // 校验用户名和密码
  req.models.user.find( {
    uname: uname,
    upwd: upwd
  }, ( err, users ) => {
    if ( err ) {
      console.log( err );
      return;
    }
    res.setHeader( 'Content-Type', 'text/html;charset=utf8' );
    if ( users != null && users.length == 1 ) {
      // 设置session
      req.session.uname = uname;
      // 清除验证码session
      req.session.vcode = null;

      res.end( "<script>alert('恭喜您,登录成功!!!');window.location.href='/video/list';</script>" );
    } else {
      res.end( "<script>alert('用户名和密码错误!!!');window.location.href='/account/login';</script>" );
    }
  } );
};

// 获取验证码
exports.getVCode = ( req, res ) => {
  // 生成随机验证码
  cosnt vcode = parseInt( Math.random() * 9000 + 1000 );
  // 写入session
  // 服务器和浏览器的session---只有服务器有session吧, 这里就是写入服务器?
  req.session.vcode = vcode;

  //创建图片
  var p = new captchapng( 80, 30, vcode ); // width,height,numeric captcha
  //背景色
  p.color( 0, 0, 0, 0 ); // First color: background (red, green, blue, alpha)
  //前景色
  p.color( 80, 80, 80, 255 ); // Second color: paint (red, green, blue, alpha)

  var img = p.getBase64();
  var imgbase64 = new Buffer( img, 'base64' );
  res.writeHead( 200, {
    'Content-Type': 'image/png'
  } );
  res.end( imgbase64 );
};

// 退出登录
exports.logout = ( req, res ) => {
  req.session.uname = null;

  res.setHeader( "Content-Type", "text/html;charset=utf-8" );
  res.end( "<script>window.location.href='/account/login';</script>" );
};
